// miniprogram/pages/statistics/history.js
Page({
  data: {
    sceneType: '',
    sceneTypeName: '',
    timeRange: 'month', // week, month, year
    chartData: [],
    totalPoints: 0,
    avgPoints: 0,
    maxPoints: 100 // 图表最大值
  },

  onLoad() {
    const app = getApp()
    this.setData({
      sceneType: app.globalData.sceneType,
      sceneTypeName: app.getSceneTypeName(app.globalData.sceneType)
    })
    this.loadHistoryData()
  },

  // 切换时间范围
  switchTimeRange(e) {
    const range = e.currentTarget.dataset.range
    this.setData({ timeRange: range })
    this.loadHistoryData()
  },

  loadHistoryData() {
    let chartData = []
    let totalPoints = 0
    let maxPoints = 100 // 默认最大值
    
    // 根据时间范围生成模拟数据
    switch (this.data.timeRange) {
      case 'week':
        chartData = [
          { date: '周一', points: 45 },
          { date: '周二', points: 30 },
          { date: '周三', points: 55 },
          { date: '周四', points: 40 },
          { date: '周五', points: 60 },
          { date: '周六', points: 25 },
          { date: '周日', points: 35 }
        ]
        maxPoints = 70 // 设置合适的最大值
        break
      case 'month':
        chartData = [
          { date: '第1周', points: 180 },
          { date: '第2周', points: 165 },
          { date: '第3周', points: 190 },
          { date: '第4周', points: 175 }
        ]
        maxPoints = 200 // 设置合适的最大值
        break
      case 'year':
        chartData = [
          { date: '1月', points: 720 },
          { date: '2月', points: 680 },
          { date: '3月', points: 750 },
          { date: '4月', points: 700 },
          { date: '5月', points: 780 },
          { date: '6月', points: 740 }
        ]
        maxPoints = 800 // 设置合适的最大值
        break
    }
    
    // 计算总积分和平均积分
    totalPoints = chartData.reduce((sum, item) => sum + item.points, 0)
    const avgPoints = Math.round(totalPoints / chartData.length)
    
    // 计算每个柱子的高度（相对于最大值的比例）
    const chartHeight = 250 // 图表高度
    chartData = chartData.map(item => {
      return {
        ...item,
        height: Math.round((item.points / maxPoints) * chartHeight)
      }
    })
    
    this.setData({ 
      chartData,
      totalPoints,
      avgPoints,
      maxPoints
    })
  },

  // 导出数据
  exportData() {
    wx.showModal({
      title: '导出数据',
      content: '数据将导出为Excel格式，是否继续？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '数据导出成功',
            icon: 'success'
          })
        }
      }
    })
  }
})